package com.fy56.platform.goodsTracking.car.api.impl;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.goodsTracking.car.api.CarUpdateApi;
import com.fy56.platform.goodsTracking.car.mode.Document;
import com.fy56.platform.goodsTracking.car.mode.Ordersynchronize;
import com.fy56.platform.goodsTracking.car.mode.Upstreamcompany;
import com.fy56.platform.goodsTracking.car.service.DocumentService;
import com.fy56.platform.goodsTracking.car.service.OrderSynchronizeService;
import com.fy56.platform.goodsTracking.car.unit.Constants;
import com.fy56.platform.goodsTracking.commons.DateUtil;
import com.fy56.platform.goodsTracking.commons.StringUtils;
import com.fy56.platform.goodsTracking.commons.constant.JrptConstants;
import com.fy56.platform.goodsTracking.commons.unit.WebUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.net.ConnectException;
import java.util.*;

/**
 * Created by XTK on 2017-04-26.
 */
@Repository
public class CarUpdateApiImpl implements CarUpdateApi {
    static Logger log = Logger.getLogger(CarUpdateApiImpl.class);
    @Autowired
    private DocumentService documentService;
    @Autowired
    private OrderSynchronizeService orderSynchronizeService;

    @Override
    public void doUpload_Track(Ordersynchronize orderSynchronize) {
        String endTime =DateUtil.before(10);
        //查询需要上传的企业
        List<Upstreamcompany> upstreamCompanyList = orderSynchronizeService.listUpstreamCompany(orderSynchronize.getOrganizationcode());
        String upstreamCompanyArray = "'fygsfy56fy56'";
        Map<String, String> upstreamCompanyMap = new HashMap<String, String>();
        for (Upstreamcompany upstreamCompany : upstreamCompanyList) {
            upstreamCompanyArray = upstreamCompanyArray + ",'" + upstreamCompany.getFinancialcode() + "'";
            upstreamCompanyMap.put(upstreamCompany.getFinancialcode(), upstreamCompany.getTrackurl());
        }
        String beginTime = orderSynchronize.getLasttime();
        if (StringUtils.isEmpty(beginTime)) {
            beginTime = DateUtil.Now();
        }
        List<Document> documentList = documentService.list(orderSynchronize.getOrganizationcode(), beginTime, endTime, upstreamCompanyArray);
        log.info("无车承运人票数" + documentList.size());
        Integer iSuccess = 0;
        for (Document d : documentList) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("identifiers", "orderTrack");
            map1.put("sendCode", orderSynchronize.getFinancialcode());
            map1.put("receiveCode", d.getConsignorcompanycode());
            map1.put("messageGuid", d.getConsignmentbillmasterid() + "-" + d.getSystime());

            Map<String, Object> map2 = new HashMap<String, Object>();
            String code;
            if (d.getDatatype().equals("1"))
                code = "05";
            else if (d.getDatatype().equals("2"))
                code = "03";
            else code = "02";
            map2.put("MessageFunctionCode", code);
            map2.put("ShippingNoteNumber", d.getConsignmentbillnumber());
            map2.put("OriginalDocumentNumber", d.getManualnumber());
            map2.put("GoodsSelfNumber", d.getGoodsnumber());
            map2.put("InHouseIdentifier", "2017");
            map2.put("TransportStatusCode", d.getTypenum());
            map2.put("StatusChangeDateTime", d.getSystime());
            map2.put("PlaceOrLocationIdentification", d.getCreatecompanyname());
            map2.put("NameOfPerson", d.getCreateoperator());
            String remark=d.getInfo();
            if (remark!=null&&remark.length()!=0){
                remark=remark.replaceAll("&","");
            }
            map2.put("Remark", remark);

            map1.put("messageObject", map2);
            map1.put("notifieUrl", "http://f6sms.feiyang56.cn:50002/server/api/v1/orderTrack/callBack");
            map1.put("stateFlag", "0");
            map1.put("remark", "");
            map1.put("destinationUrl", upstreamCompanyMap.get(d.getConsignorcompanycode()));

            String postContent = "loginName=" + orderSynchronize.getUsername() + "&loginPwd=" + orderSynchronize.getPassword()
                    + "&companyCode=" + orderSynchronize.getFinancialcode() + "&strType=JSON&jsonVersion=1.0"
                    + "&documentData=" + JSON.toJSONString(map1);
            log.info(postContent);
            Integer retryTime = 0;

            while (retryTime < 3) {
                try {
                    String rsp = WebUtils.doPost(Constants.url, postContent, JrptConstants.CHARSET_UTF8, 10000, 10000);
                    log.info("上传无车承运人单据" + rsp);
                    iSuccess++;
                    break;
                } catch (ConnectException e) {
                    retryTime++;
                    log.error("请求超时，重试" + retryTime + "次", e);
                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
        //更新上次上传时间
        if (iSuccess > 0)
            orderSynchronizeService.updateLastTime(orderSynchronize.getOrganizationcode(), endTime);

    }

    public static void main(String args[]) {

        System.out.print(DateUtil.before(10));
    }
}
